package Database;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;

public class DBManager {

    /*
     * clase DBManager
     *
     * Un objeto DBLoader se conecta a la base de datos y almacena los datos de
     * esta en estructuras internas.
     *
     * IMPORTANTE: solo accede a bases de datos con el driver Derby
     *
     */
    private String dbName;
    private String userName;
    private String password;
    private Connection con;

    public DBManager(String dbName, String userName, String password) {
        this.dbName = dbName;
        this.userName = userName;
        this.password = password;
    }

    public ResultSet executeQuery(String query1) throws SQLException {
        PreparedStatement query = con.prepareStatement(query1, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet result = query.executeQuery();
        return result;
    }

    public void execute(String query1) throws SQLException {
        PreparedStatement query = con.prepareStatement(query1);
        query.execute();
    }

    public boolean tableExist(String tableName) {
        try {
            DatabaseMetaData dbmd = con.getMetaData();
            ResultSet rs = dbmd.getTables(null, null, tableName, null);
            if (!rs.next()) {
                return false;
            } else {
                return true;
            }
        } catch (Exception except) {
            except.printStackTrace();
            return false;
        }
    }

    public void connect() throws SQLException {
        con = ConnectionProvider.getInstance().getConnection("jdbc:derby://localhost:1527/" + dbName + ";create=false", userName, password);
    }

    public boolean isConnected() {
        return con != null;
    }
}
